#notrequire:host\get-ping

param(
	[string]$vmstorepath = "D:\vms",
	[string]$vmrunpath = "C:\Program Files\VMware\VMware Workstation\vmrun.exe",
	[string]$7zpath = "C:\Program Files\7-Zip\7z.exe",
	[string]$name,
	[string]$template
)
#Write-Host $name
#Write-Host $template
$fullpath = Join-Path (Join-Path $vmstorepath $name) "$name.vmx"
$templatespath = Join-Path (Split-Path $MyInvocation.MyCommand.Path) "template"
$templatepath = Join-Path $templatespath ("$template\$template"+"TEMPLATE.vmx")
#Write-Host $fullpath
Write-Host -foreground "green" "cloning" 
if(Test-Path $fullpath) {
	Write-Host -foreground "blue" "cloning ... skipping (already exists)"
} else {
	$src = Join-Path $templatespath "$template.zip"
	$dest = Join-Path $templatespath "$template"
	if(!(Test-Path $dest)) {
		if(!(Test-Path $7zpath)) {
			throw "7z.exe not found, unzip vm templates manually"
		}
		& $7zpath "e" "$src" "-o$dest" "-y"
	}
	if(!(Test-Path $templatepath)) {
		Write-Error "Template has not been un-zipped: $templatepath"
		1
	} else {
		$job = start-job -ArgumentList @($vmrunpath, $templatepath, $fullpath) { 
			param($vmrunpath, $templatepath, $fullpath)
			& $vmrunpath "-T" "ws" "clone" $templatepath $fullpath "full"
		}
		wait-job $job
		receive-job $job 
		Write-Host -foreground "blue" "cloning ... done" 
		Write-Host -foreground "green" "configuring" 
		(Get-Content $fullpath) | where {$_ -notmatch "displayName" } | Set-Content $fullpath
		Add-Content $fullpath ('displayName = "' + $name + '"')
		Write-Host -foreground "blue" "configuring ... done" 
	}
}
0
